import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_constraintlayout/flutter_constraintlayout.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:get/get.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:zrjz/comm/base/base.dart';
import 'package:zrjz/comm/base/base_state.dart';
import 'package:zrjz/comm/base/base_stateful_page.dart';
import 'package:zrjz/comm/constants/color_constants.dart';
import 'package:zrjz/comm/constants/constants.dart';
import 'package:zrjz/comm/service/config.dart';
import 'package:zrjz/comm/utils/device_utils.dart';
import 'package:zrjz/comm/utils/ex_widget.dart';
import 'package:zrjz/comm/utils/ext_dart.dart';
import 'package:zrjz/comm/utils/log_utils.dart';
import 'package:zrjz/comm/widget/common_widget.dart';
import 'package:zrjz/comm/widget/my_button.dart';
import 'package:zrjz/comm/widget/my_load_image.dart';
import 'package:zrjz/comm/widget/my_text_field.dart';
import 'package:zrjz/comm/widget/my_text_view.dart';
import 'package:zrjz/generated/assets.dart';
import 'package:zrjz/local/theme/theme_config.dart';
import 'package:zrjz/modules/auth/login/login_state.dart';
import 'package:zrjz/router/page_router.dart';

import 'login_controller.dart';

class LoginPage extends BaseStatefulPage<LoginController> {
  LoginPage({super.key});

  static void startInstance([LaunchModel launchModel = LaunchModel.singleTop]) {
    return Get.start(RouterPath.AUTH_LOGIN, launchModel: launchModel);
  }

  static void offAllNamed() {
    Get.offAllNamed(RouterPath.AUTH_LOGIN); //关闭全部页面进入登录
  }

  @override
  State<LoginPage> createState() => _LoginPageState();

  @override
  LoginController createRawController() {
    return LoginController();
  }
}

class _LoginPageState extends BaseState<LoginPage, LoginController> with StateLifecycle {

  late LoginState state;

  @override
  void initState() {
    super.initState();
    state = controller.state;
  }

  @override
  void onResume() {
    super.onResume();
    Log.d("LoginPage Lifecycle - onResume");
  }

  @override
  void onPause() {
    super.onPause();
    Log.d("LoginPage Lifecycle - onPause");
  }

  @override
  void onStop() {
    super.onStop();
    Log.d("LoginPage Lifecycle - onStop");
  }

  @override
  void onStart() {
    super.onStart();
    Log.d("LoginPage Lifecycle - onStart");
  }

  @override
  Widget build(BuildContext context) {
    Log.d("LoginPage Lifecycle - build走了一遍");
    ConstraintId imgBG = ConstraintId('imgBG');

    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: Get.isDarkMode ? ThemeConfig.systemUiOverlayStyleDarkTheme : ThemeConfig.systemUiOverlayStyleLightThemeWhite,
      child: Scaffold(
          backgroundColor: DarkThemeUtil.multiColors(ColorConstants.white, darkColor: ColorConstants.darkBlackBg),
          body: SafeArea(
            bottom: true,
            top: false,
            child: GetBuilder<LoginController>(
                tag: widget.key?.toString(),
                builder: (controller) {
                  return ConstraintLayout(
                    width: matchParent,
                    height: matchParent,
                    children: [
                      // 顶部的图片背景
                      MyAssetImage(
                        Get.isDarkMode ? Assets.authLoginTopBgDark : Assets.authLoginTopBg,
                        fit: BoxFit.fill,
                      ).applyConstraint(
                        id: imgBG,
                        width: matchConstraint,
                        //宽度按约束的父布局宽高铺满
                        height: matchConstraint,
                        //高度按宽度的比例来计算
                        widthHeightRatio: 375 / 180.5,
                        top: parent.top,
                        left: parent.left,
                        right: parent.right,
                      ),

                      //底部的表单与选项
                      SingleChildScrollView(
                        scrollDirection: Axis.vertical,
                        physics: const BouncingScrollPhysics(),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            //中间的Logo
                            const MyAssetImage(
                              Assets.authLoginLogoIcon,
                              height: 103,
                              width: 103,
                            ),

                            Column(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                // 登录表单 - 电话号码
                                _buildInputLayout(
                                  "phone",
                                  Assets.authLoginPhoneIcon,
                                  leftIconWidth: 13.5,
                                  leftIconHeight: 16,
                                  textInputType: TextInputType.phone,
                                  textInputAction: TextInputAction.next,
                                  errorText: controller.mobilePhoneErrorText,
                                  onSubmit: (formKey, value) {
                                    state.formData[formKey]!['focusNode'].unfocus();
                                    FocusScope.of(context).requestFocus(state.formData['password']!['focusNode']);
                                  },
                                ),

                                // 登录表单 - 密码
                                _buildInputLayout(
                                  "password",
                                  Assets.authLoginPasswordIcon,
                                  leftIconWidth: 13.5,
                                  leftIconHeight: 16,
                                  marginTop: 10,
                                  obscureText: !controller.pwdVisibility,
                                  errorText: controller.passwordErrorText,
                                  showRightIcon: true,
                                  rightWidget: IconButton(
                                    highlightColor: Colors.transparent,
                                    splashColor: Colors.transparent,
                                    icon: controller.pwdVisibility
                                        ? const MyAssetImage(Assets.authLoginPasswordVisIcon, width: 20.5, height: 13)
                                        : const MyAssetImage(Assets.authLoginPasswordInvisIcon, width: 20.5, height: 13),
                                    onPressed: () {
                                      controller.switchPwdVisibility();
                                    },
                                  ),
                                  onSubmit: (formKey, value) {
                                    state.formData[formKey]!['focusNode'].unfocus();
                                    controller.doInputLogin();
                                  },
                                ),

                                //登录按钮
                                MyButton(
                                  text: "登 录".tr,
                                  textColor: ColorConstants.white,
                                  fontSize: 17,
                                  fontWeight: FontWeight.w700,
                                  backgroundColor: ColorConstants.appBlue,
                                  minHeight: 45,
                                  radius: 5,
                                  type: ClickType.throttle,
                                  milliseconds: 1000,
                                  onPressed: () => controller.doInputLogin(),
                                ).marginOnly(left: 28.5, right: 28.5, top: 23),

                                //电话号码一键登录
                                MyButton(
                                  text: "本机号码一键登录".tr,
                                  fontSize: 17,
                                  fontWeight: FontWeight.w700,
                                  textColor: ColorConstants.white,
                                  backgroundColor: ColorConstants.appGreen,
                                  minHeight: 45,
                                  radius: 5,
                                  type: ClickType.throttle,
                                  milliseconds: 1000,
                                  onPressed: () => controller.loginQuickWithPhone(),
                                ).marginOnly(left: 28.5, right: 28.5, top: 10),

                                //注册与忘记密码的Row
                                _buildSignForgetRow(),

                                //同意协议
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    MyAssetImage(
                                      controller.isChecked ? Assets.authCheckboxChoose : Assets.authCheckboxUnchoose,
                                      width: 14.0,
                                      height: 13.0,
                                    ).padding(all: 5).onTap(() {
                                      controller.handlerSelectAgreeCheckbox();
                                    }),
                                    const SizedBox(
                                      width: 6,
                                    ),
                                    Column(
                                      crossAxisAlignment: CrossAxisAlignment.center,
                                      children: [
                                        MyTextView(
                                          '已阅读并同意Room的'.tr,
                                          textColor: DarkThemeUtil.multiColors(ColorConstants.gray76, darkColor: ColorConstants.white),
                                          fontSize: 14,
                                          isFontMedium: true,
                                        ),
                                        Row(
                                          children: [
                                            MyTextView(
                                              '免责条款'.tr,
                                              textColor: ColorConstants.appBlue,
                                              fontSize: 14,
                                              isFontMedium: true,
                                              onClick: () {
                                                controller.gotoUserAgreementPage();
                                              },
                                            ),
                                            MyTextView(
                                              ' 和 '.tr,
                                              textColor: DarkThemeUtil.multiColors(ColorConstants.gray76, darkColor: ColorConstants.white),
                                              fontSize: 14,
                                              isFontMedium: true,
                                            ),
                                            MyTextView(
                                              '隐私条款'.tr,
                                              textColor: ColorConstants.appBlue,
                                              fontSize: 14,
                                              isFontMedium: true,
                                              onClick: () {
                                                controller.gotoPricacyPolicyPage();
                                              },
                                            ),
                                          ],
                                        )
                                      ],
                                    ),
                                  ],
                                ).marginSymmetric(vertical: 29),

                                //其它登录方式Row
                                Visibility(
                                    visible: Device.isIOS ? true : controller.isInstallWx || controller.isInstallWx,
                                    child: Row(
                                      children: [
                                        const MyAssetImage(
                                          Assets.authLoginLineBg,
                                          width: 110,
                                        ),
                                        const Spacer(),
                                        MyTextView(
                                          '其它登录方式'.tr,
                                          textColor: DarkThemeUtil.multiColors(ColorConstants.black, darkColor: ColorConstants.white),
                                          fontSize: 12,
                                          isFontMedium: true,
                                        ),
                                        const Spacer(),
                                        const MyAssetImage(
                                          Assets.authLoginLineBg,
                                          width: 110,
                                        ),
                                      ],
                                    ).marginOnly(left: 28.5, right: 28.5, bottom: 20)),

                                //微信QQ登录的Row
                                Visibility(
                                    visible: Device.isIOS ? true : controller.isInstallWx || controller.isInstallWx,
                                    child: Row(
                                      mainAxisAlignment: MainAxisAlignment.center,
                                      children: _buildThirdPartyLogs(),
                                    ).marginOnly(left: 28.5, right: 28.5, bottom: 18)),

                                //底部信息的Row
                                MyTextView(
                                  '使用第三方首次登录，需要绑定手机号'.tr,
                                  fontSize: 13,
                                  // marginTop: 18,
                                  textColor: ColorConstants.gray99,
                                  isFontMedium: true,
                                ),

                                // 底部信息的Row，带跳转
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    MyTextView(
                                      '举报监督电话  |'.tr,
                                      fontSize: 13,
                                      textColor: ColorConstants.gray99,
                                      isFontMedium: true,
                                      onClick: () => controller.showCallPhone(),
                                    ),
                                    MyTextView(
                                      '  人力资源服务许可证  '.tr,
                                      fontSize: 13,
                                      textColor: ColorConstants.gray99,
                                      isFontMedium: true,
                                      onClick: () => controller.showHRCertificate(),
                                    ),
                                    MyTextView(
                                      '|  营业执照'.tr,
                                      fontSize: 13,
                                      textColor: ColorConstants.gray99,
                                      isFontMedium: true,
                                      onClick: () => controller.showBusinessLicense(),
                                    ),
                                  ],
                                ),

                                CommonWidget.rowHeight(),
                              ],
                            ).backgroundColor(DarkThemeUtil.multiColors(
                              ColorConstants.white,
                              darkColor: ColorConstants.darkBlackBg,
                            )),
                          ],
                        ),
                      ).applyConstraint(
                        width: matchConstraint,
                        height: matchConstraint,
                        top: imgBG.bottom.margin(-(51.5)),
                        bottom: parent.bottom,
                        left: parent.left,
                        right: parent.right,
                      )
                    ],
                  );
                }),
          )),
    );
  }

  /// 输入框 电话与密码
  _buildInputLayout(
    String key,
    String leftIconRes, {
    double leftIconWidth = 0,
    double leftIconHeight = 0,
    double marginTop = 23,
    bool? showRightIcon = false, //是否展示右侧的布局
    Widget? rightWidget, //右侧的布局
    TextInputType textInputType = TextInputType.text,
    String? errorText,
    bool obscureText = false,
    TextInputAction textInputAction = TextInputAction.done,
    Function? onSubmit,
  }) {
    return IgnoreKeyboardDismiss(
      child: MyTextField(
        key,
        state.formData[key]!['value'],
        hintText: state.formData[key]!['hintText'],
        hintStyle: TextStyle(
          color: DarkThemeUtil.multiColors(ColorConstants.gray99, darkColor: ColorConstants.white),
          fontSize: 14.0,
          fontWeight: FontWeight.w500,
        ),
        controller: state.formData[key]!['controller'],
        focusNode: state.formData[key]!['focusNode'],
        margin: EdgeInsets.only(left: 28.5, right: 28.5, top: marginTop),
        showDivider: true,
        dividerColor: DarkThemeUtil.multiColors(ColorConstants.dividerItem, darkColor: ColorConstants.darkBlackItemDivider),
        style: TextStyle(
          color: DarkThemeUtil.multiColors(ColorConstants.tabTextBlack, darkColor: ColorConstants.white),
          fontSize: 14.0,
          fontWeight: FontWeight.w500,
        ),
        inputType: textInputType,
        textInputAction: textInputAction,
        onSubmit: onSubmit,
        cursorColor: ColorConstants.tabTextBlack,
        obscureText: obscureText,
        errorText: errorText,
        showLeftIcon: true,
        showRightIcon: showRightIcon,
        rightWidget: rightWidget,
        leftWidget: Row(
          children: [
            MyAssetImage(leftIconRes, width: leftIconWidth, height: leftIconHeight),
            const Spacer(),
            Container(
              color: ColorConstants.graye5,
              width: 1,
              height: 15,
            )
          ],
        ).constrained(width: 30),
      ),
    );
  }

  /// 第三方登录
  List<Widget> _buildThirdPartyLogs() {
    if (Device.isIOS && int.parse(ConfigService.to.iosDeviceInfo?.systemVersion!.split(".").first ?? "12") >= 13) {
      return [
        //QQ
        Visibility(
            visible: controller.isInstallQQ,
            child: GestureDetector(
              onTap: () {
                controller.thirdPartWithQQ();
              },
              behavior: HitTestBehavior.opaque,
              child: const MyAssetImage(
                Assets.authLoginQqIcon,
                width: 46,
                height: 46,
              ).marginOnly(right: 20),
            )),

        //微信
        Visibility(
            visible: controller.isInstallWx,
            child: GestureDetector(
              onTap: () {
                controller.thirdPartWithWX();
              },
              behavior: HitTestBehavior.opaque,
              child: const MyAssetImage(
                Assets.authLoginWxIcon,
                width: 46,
                height: 46,
              ).marginOnly(right: 20),
            )),
        //Apple登陆
        GestureDetector(
          onTap: () {
            controller.thirdPartWithApple();
          },
          behavior: HitTestBehavior.opaque,
          child: const MyAssetImage(
            Assets.authLoginAppleIcon,
            width: 46,
            height: 46,
          ),
        ),
      ];
    } else {
      return [
        //QQ
        Visibility(
            visible: controller.isInstallQQ,
            child: GestureDetector(
              onTap: () {
                controller.thirdPartWithQQ();
              },
              behavior: HitTestBehavior.opaque,
              child: const MyAssetImage(
                Assets.authLoginQqIcon,
                width: 46,
                height: 46,
              ).marginOnly(right: 20),
            )),

        //微信
        Visibility(
            visible: controller.isInstallWx,
            child: GestureDetector(
              onTap: () {
                controller.thirdPartWithWX();
              },
              behavior: HitTestBehavior.opaque,
              child: const MyAssetImage(
                Assets.authLoginWxIcon,
                width: 46,
                height: 46,
              ),
            )),
      ];
    }
  }

  /// 忘记密码，注册账号
  _buildSignForgetRow() {
    return Row(
      children: [
        MyTextView(
          '没有帐号？'.tr,
          textColor: DarkThemeUtil.multiColors(ColorConstants.black, darkColor: ColorConstants.white),
          fontSize: 14,
          isFontMedium: true,
        ),
        //注册文本
        GestureDetector(
          onTap: () => controller.gotoSignUpPage(),
          behavior: HitTestBehavior.opaque,
          child: MyTextView(
            '注册'.tr,
            textColor: ColorConstants.appBlue,
            fontSize: 14,
            isFontMedium: true,
          ),
        ),
        const Spacer(),
        //忘记密码
        GestureDetector(
          onTap: () => controller.gotoForgetPsdPage(),
          behavior: HitTestBehavior.opaque,
          child: MyTextView(
            '忘记密码'.tr,
            textColor: ColorConstants.appBlue,
            fontSize: 14,
            isFontMedium: true,
          ),
        ),
      ],
    ).marginOnly(left: 28.5, right: 28.5, top: 15);
  }

  @override
  void dispose() {
    Get.delete<LoginController>();
    super.dispose();
  }
}
